var db = require("../util/DataBase.js");

var topicService = require("../service/topic.js");
var userService = require("../service/user.js");

var ALY = require("aliyun-sdk");

var push = new ALY.PUSH({
      accessKeyId: 'LTAIaO6zxMnMEY05',
      secretAccessKey: 'rKZ3xiiHCfA8aVlWWMArZX1v4Pvb2T',
      endpoint: 'http://cloudpush.aliyuncs.com',
      apiVersion: '2016-08-01'
    }
);

var questionMsgSended = {};

var service = {
  triggerPushNotification(userId, title, content, extParams) {

    userService.getDeviceList(userId, (deviceList) => {

      service.unread(userId, (count) => {

        var deviceIdList = [];
        deviceList.forEach((device) => {
          deviceIdList.push(device.push_device_id);
        });

        push.push({
          AppKey: '25358042',
          //推送目标: DEVICE:按设备推送 ALIAS : 按别名推送 ACCOUNT:按帐号推送  TAG:按标签推送; ALL: 广播推送
          Target: 'DEVICE',
          //根据Target来设定，如Target=DEVICE, 则对应的值为 设备id1,设备id2. 多个值使用逗号分隔.(帐号与设备有一次最多100个的限制)
          TargetValue: deviceIdList.join(","),
          PushType: "NOTICE", //消息类型 MESSAGE NOTICE
          //设备类型 ANDROID iOS ALL.
          DeviceType: "iOS",
          Title: title,
          Body: content,
          //iOS相关配置
          iOSBadge: count,//iOS应用图标右上角角标
          iOSMusic: 'default',//iOS通知声音
          iOSApnsEnv: 'PRODUCT',//iOS的通知是通过APNs中心来发送的，需要填写对应的环境信息。"DEV" : 表示开发环境 "PRODUCT" : 表示生产环境
          iOSRemind: true,//消息推送时设备不在线（既与移动推送的服务端的长连接通道不通），则这条推送会做为通知，通过苹果的APNs通道送达一次。注意：离线消息转通知仅适用于生产环境
          iOSRemindBody: "iOSReminfBody",//iOS消息转通知时使用的iOS通知内容，仅当iOSApnsEnv=PRODUCT && iOSRemind为true时有效
          iOSExtParameters: extParams,//通知的扩展属性(注意 : 该参数要以json map的格式传入,否则会解析出错)
          //android相关配置
          AndroidNotifyType: "BOTH", //通知的提醒方式 "VIBRATE" : 震动 "SOUND" : 声音 "BOTH" : 声音和震动 NONE : 静音
          AndroidNotificationBarType: 1, //通知栏自定义样式0-100
          AndroidOpenType: "URL", //点击通知后动作 "APPLICATION" : 打开应用 "ACTIVITY" : 打开AndroidActivity "URL" : 打开URL "NONE" : 无跳转
          AndroidOpenUrl: "http://www.aliyun.com", //Android收到推送后打开对应的url,仅当AndroidOpenType="URL"有效
          AndroidActivity: "com.alibaba.push2.demo.XiaoMiPushActivity", //设定通知打开的activity,仅当AndroidOpenType="Activity"有效
          AndroidXiaoMiActivity: "com.ali.demo.MiActivity", //设置该参数后启动小米托管弹窗功能, 此处指定通知点击后跳转的Activity（托管弹窗的前提条件：1. 集成小米辅助通道；2. StoreOffline参数设为true）
          AndroidExtParameters: extParams, //通知的扩展属性(注意 : 该参数要以json map的格式传入,否则会解析出错)
          AndroidXiaoMiNotifyTitle: "xiaomititle",
          AndroidXiaoMiNotifyBody: "xiaomibody",
          //推送控制
          //可以设置成你指定固定时间
          PushTime: (new Date((new Date()).getTime())).toISOString().replace(/\.\d\d\d/g,''),
          // 离线消息的过期时间，过期则不会再被发送。离线消息最长保存72小时，过期时间时长不会超过发送时间加72小时。时间格式按照ISO8601标准表示，并需要使用UTC时间，格式为YYYY-MM-DDThh:mm:ssZ
          ExpireTime: (new Date((new Date()).getTime() + 12 * 3600 * 1000)).toISOString().replace(/\.\d\d\d/g,''),
          StoreOffline: false//离线消息是否保存,若保存, 在推送时候，用户即使不在线，下一次上线则会收到
        }, function (err, res) {
          console.log(err, res);
        });

        push.push({
          AppKey: '26013995',
          //推送目标: DEVICE:按设备推送 ALIAS : 按别名推送 ACCOUNT:按帐号推送  TAG:按标签推送; ALL: 广播推送
          Target: 'DEVICE',
          //根据Target来设定，如Target=DEVICE, 则对应的值为 设备id1,设备id2. 多个值使用逗号分隔.(帐号与设备有一次最多100个的限制)
          TargetValue: deviceIdList.join(","),
          PushType: "NOTICE", //消息类型 MESSAGE NOTICE
          //设备类型 ANDROID iOS ALL.
          DeviceType: "ANDROID",
          Title: title,
          Body: content,
          //iOS相关配置
          iOSBadge: count,//iOS应用图标右上角角标
          iOSMusic: 'default',//iOS通知声音
          iOSApnsEnv: 'PRODUCT',//iOS的通知是通过APNs中心来发送的，需要填写对应的环境信息。"DEV" : 表示开发环境 "PRODUCT" : 表示生产环境
          iOSRemind: true,//消息推送时设备不在线（既与移动推送的服务端的长连接通道不通），则这条推送会做为通知，通过苹果的APNs通道送达一次。注意：离线消息转通知仅适用于生产环境
          iOSRemindBody: "iOSReminfBody",//iOS消息转通知时使用的iOS通知内容，仅当iOSApnsEnv=PRODUCT && iOSRemind为true时有效
          iOSExtParameters: extParams,//通知的扩展属性(注意 : 该参数要以json map的格式传入,否则会解析出错)
          //android相关配置
          AndroidNotifyType: "BOTH", //通知的提醒方式 "VIBRATE" : 震动 "SOUND" : 声音 "BOTH" : 声音和震动 NONE : 静音
          AndroidNotificationBarType: 1, //通知栏自定义样式0-100
          AndroidOpenType: "APPLICATION", //点击通知后动作 "APPLICATION" : 打开应用 "ACTIVITY" : 打开AndroidActivity "URL" : 打开URL "NONE" : 无跳转
          AndroidOpenUrl: "http://www.aliyun.com", //Android收到推送后打开对应的url,仅当AndroidOpenType="URL"有效
          AndroidActivity: "com.alibaba.push2.demo.XiaoMiPushActivity", //设定通知打开的activity,仅当AndroidOpenType="Activity"有效
          AndroidXiaoMiActivity: "com.ali.demo.MiActivity", //设置该参数后启动小米托管弹窗功能, 此处指定通知点击后跳转的Activity（托管弹窗的前提条件：1. 集成小米辅助通道；2. StoreOffline参数设为true）
          AndroidExtParameters: extParams, //通知的扩展属性(注意 : 该参数要以json map的格式传入,否则会解析出错)
          AndroidXiaoMiNotifyTitle: "xiaomititle",
          AndroidXiaoMiNotifyBody: "xiaomibody",
          AndroidNotificationChannel: "1",
          //辅助弹窗
          AndroidPopupActivity: "cn.aperturenx.banxian.PopupPushActivity",
          AndroidPopupTitle: title,
          AndroidPopupBody: content,
          //推送控制
          //可以设置成你指定固定时间
          PushTime: (new Date((new Date()).getTime())).toISOString().replace(/\.\d\d\d/g,''),
          // 离线消息的过期时间，过期则不会再被发送。离线消息最长保存72小时，过期时间时长不会超过发送时间加72小时。时间格式按照ISO8601标准表示，并需要使用UTC时间，格式为YYYY-MM-DDThh:mm:ssZ
          ExpireTime: (new Date((new Date()).getTime() + 12 * 3600 * 1000)).toISOString().replace(/\.\d\d\d/g,''),
          StoreOffline: true//离线消息是否保存,若保存, 在推送时候，用户即使不在线，下一次上线则会收到
        }, function (err, res) {
          console.log(err, res);
        });

      });



    }, () => {

    });



  },
  unread(userId, success, error) {

    db.query("SELECT count(inbox.id) as `count` FROM `inbox`, `message` WHERE message.id = inbox.message_id AND message.type <> 'question' AND `read` = 0 AND `user_id` = ?", [
      userId
    ], function (err, results) {
      if(err) {
        error(-1, "获取未读消息数失败");
      } else {
        success(results[0].count);
      }
    });

  },
  getMessageList(userId, type, startId, len, dir, success, error) {

    db.query("SELECT inbox.id, inbox.read, inbox.message_id, inbox.user_id, message.datetime, message.type, message.data FROM inbox, message WHERE ( message.type = ? " + ( type == "reply" ? " OR message.type = 'replyComment' " : "" ) + " ) AND message.id = inbox.message_id AND inbox.user_id = ? AND inbox.id " + ( dir == "up" ? ">" : "<" ) + " ? ORDER BY inbox.id DESC LIMIT ?", [
      type,
      userId,
      startId,
      len
    ], function (err, results) {
      if(err) {
        error && error("获取消息列表失败");
      } else {

        if(results.length == 0) {
          success && success([]);

        } else {

          success && success(results);

        }

      }
    });
  },
  getMessageContent(messageId, success, error) {

    db.query("SELECT id, datetime, type, data FROM message WHERE id = ?", [
      messageId
    ], function (err, results) {
      if(err) {
        error && error("获取消息实体失败");
      } else {

        if(results.length == 0) {
          success && success([]);

        } else {

          var msgContent = results[0];

          switch(msgContent.type) {
            case "question":
              var data = msgContent.data;

              data = data.split("_");
              var topicId = data[0], articleId = data[1];

              db.query("SELECT id, title, content, question, user_id, create_datetime FROM article WHERE id = ?", [
                articleId
              ], function (err, results) {
                if(err) {
                  error("获取消息实体失败");
                } else {
                  success(results[0]);
                }
              })
            break;
            case "answer":

              var data = msgContent.data;

              data = data.split("_");
              var articleId = data[0], replyId = data[1];

              db.query("SELECT id, title, content, question, user_id, create_datetime FROM article WHERE id = ?", [
                articleId
              ], function (err, results) {
                if(err) {
                  error("获取消息实体失败");
                } else {

                  db.query(
                    "SELECT reply.id as id, `article_id`, `content`, `answer`, `user_id`, user.avatar_url as user_avatar_url, user.nickname as user_nickname FROM `reply`, `user` WHERE reply.id = ? AND reply.user_id = user.id",
                    [
                      replyId
                    ],
                    function (err, answerResults) {
                      if(err) {
                        error ("获取答案评论失败");
                      } else {
                        success({
                          article: results[0],
                          reply: answerResults[0]
                        })
                      }
                    }
                  )
                }
              })

            break;
            case "replyComment":

              var data = msgContent.data;

              data = data.split("_");
              var targetReplyId = data[0], replyId = data[1];

              db.query("SELECT reply.id as id, `article_id`, `content`, `answer`, `user_id`, user.avatar_url as user_avatar_url, user.nickname as user_nickname FROM `reply`, `user` WHERE reply.id = ? AND reply.user_id = user.id", [
                targetReplyId
              ], function (err, results) {
                if(err) {
                  error("获取消息实体失败");
                } else {

                  db.query(
                    "SELECT reply.id as id, `article_id`, `content`, `answer`, `user_id`, user.avatar_url as user_avatar_url, user.nickname as user_nickname FROM `reply`, `user` WHERE reply.id = ? AND reply.user_id = user.id",
                    [
                      replyId
                    ],
                    function (err, answerResults) {
                      if(err) {
                        error ("获取评论失败");
                      } else {
                        success({
                          targetReply: results[0],
                          reply: answerResults[0],
                          replyComment: true
                        })
                      }
                    }
                  )

                }
              })

            break;
            case "reply":

              var data = msgContent.data;

              data = data.split("_");
              var articleId = data[0], replyId = data[1];

              db.query("SELECT id, title, content, question, user_id, create_datetime FROM article WHERE id = ?", [
                articleId
              ], function (err, results) {
                if(err) {
                  error("获取消息实体失败");
                } else {

                  db.query(
                    "SELECT reply.id as id, `article_id`, `content`, `answer`, `user_id`, user.avatar_url as user_avatar_url, user.nickname as user_nickname FROM `reply`, `user` WHERE reply.id = ? AND reply.user_id = user.id",
                    [
                      replyId
                    ],
                    function (err, answerResults) {
                      if(err) {
                        error ("获取评论失败");
                      } else {
                        success({
                          article: results[0],
                          reply: answerResults[0]
                        })
                      }
                    }
                  )

                }
              })

            break;
          }

        }

      }
    });

  },
  fire(type, data, pnParams, success, error) {
    db.query("INSERT INTO `message` (`type`, `data`, `datetime`) VALUES (?, ?, ?)", [
      type,
      data,
      new Date()
    ], function (err, results) {
      if(err) {
        error && error("发送消息失败")
      } else {

        switch(type) {
          case "replyComment":
            data = data.split("_");
            var targetReplyId = data[0], replyId = data[1];

            db.query("SELECT `user_id`, `content` FROM `reply` WHERE `id` = ?", [
              targetReplyId
            ], function (err, replyResults) {
              if(err) {
                error && error("获取帖子作者失败");
              } else {

                db.query("INSERT INTO `inbox` (`message_id`, `read`, `user_id`) VALUES (?, ?, ?)", [
                  results.insertId,
                  0,
                  replyResults[0].user_id
                ], function (err, insertInboxResults) {
                  if(err) {

                  } else {

                    service.triggerPushNotification(replyResults[0].user_id, "讨论 " + replyResults[0].content, pnParams.nickname + "：" + pnParams.content, JSON.stringify({
                      targetReplyId: targetReplyId,
                      replyId: replyId,
                      type: "reply_comment",
                      inboxId: insertInboxResults.insertId
                    }));

                  }

                });

              }
            });

          break;
          case "reply":
            data = data.split("_");
            var articleId = data[0], replyId = data[1];

            db.query("SELECT `user_id`, `title` FROM `article` WHERE `id` = ?", [
              articleId
            ], function (err, articleResults) {
              if(err) {
                error && error("获取帖子作者失败");
              } else {

                db.query("INSERT INTO `inbox` (`message_id`, `read`, `user_id`) VALUES (?, ?, ?)", [
                  results.insertId,
                  0,
                  articleResults[0].user_id
                ], function (err, insertInboxResults) {
                  if(err) {

                  } else {

                    service.triggerPushNotification(articleResults[0].user_id, "讨论 " + articleResults[0].title, pnParams.nickname + "：" + pnParams.content, JSON.stringify({
                      articleId: articleId,
                      replyId: replyId,
                      type: "reply",
                      inboxId: insertInboxResults.insertId
                    }));

                  }

                });

              }
            });

          break;
          case "answer":
            data = data.split("_");
            var articleId = data[0], replyId = data[1];

            db.query("SELECT `user_id`, `title` FROM `article` WHERE `id` = ?", [
              articleId
            ], function (err, articleResults) {
              if(err) {
                error && error("获取帖子作者失败");
              } else {

                db.query("INSERT INTO `inbox` (`message_id`, `read`, `user_id`) VALUES (?, ?, ?)", [
                  results.insertId,
                  0,
                  articleResults[0].user_id
                ], function (err, insertInboxResults) {
                  if(err) {

                  } else {

                    service.triggerPushNotification(articleResults[0].user_id, "解答 " + articleResults[0].title, pnParams.nickname + "：" + pnParams.content, JSON.stringify({
                      articleId: articleId,
                      replyId: replyId,
                      type: "answer",
                      inboxId: insertInboxResults.insertId
                    }));

                  }

                });
              }
            });

          break;
          case "question":
            data = data.split("_");
            var topicId = data[0], articleId = data[1];

            topicService.getFollowUserTopic(topicId, function (followUserTopicList) {

              for(var i = 0, l = followUserTopicList.length; i < l; ++ i) {

                var userId = followUserTopicList[i].user_id;

                if(questionMsgSended[userId] && questionMsgSended[userId][articleId]) {
                  continue;
                }

                questionMsgSended[userId] = questionMsgSended[userId] || {};
                questionMsgSended[userId][articleId] = true;

                db.query("INSERT INTO `inbox` (`message_id`, `read`, `user_id`) VALUES (?, ?, ?)", [
                  results.insertId,
                  0,
                  userId
                ], function () {

                });

              }
            });

          break;
        }

        success && success(results.insertId);
      }
    });
  }
};

module.exports = service;
